<!DOCTYPE HTML>
<html lang="zh-cn">

<head>
    <meta charset="utf-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta content="width=device-width,initial-scale=1.0" name="viewport">
    <meta content="yes" name="apple-mobile-web-app-capable">
    <meta content="black" name="apple-mobile-web-app-status-bar-style">
    <meta content="telephone=no" name="format-detection">
    <meta content="email=no" name="format-detection">
    <title>系统管理</title>
    <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.bootcss.com/bootstrap-table/1.11.1/bootstrap-table.min.css" rel="stylesheet">
    <link rel="stylesheet" href=https://cdn.bootcss.com/jquery-treegrid/0.2.0/css/jquery.treegrid.min.css>
</head>

<body>
<div class="container">
    <div class="ibox-content">
        <div class="row">
            <div class="col-sm-12">
                <div class="form-inline  text-left">
                    <div class="form-group ">
                        <label class="control-label m-b-xs" for="repositoryId">资源库：</label>
                        <select id="repositoryId" name="repositoryId" class="form-control m-b-xs" aria-required="true"
                                onchange="changeRep(this)">
                            <option value="" selected>请选择资源库</option>
                        </select>
                    </div>
                    <div class="form-group ">
                        <label class="control-label m-b-xs" for="transName">转换名称：</label>
                        <input id="transName" name="transName" type="text" placeholder="请输入转换名称"
                               class="form-control m-b-xs" aria-required="true">
                    </div>
                    <div class="form-group">
                        <button onclick="search()" class="btn btn-w-m btn-info" type="button">
                            <i class="fa fa-search" aria-hidden="true"></i>&nbsp;搜索
                        </button>
                    </div>
                </div>
            </div>
        </div>
        <table id="transList">
        </table>
    </div>
    <table id="table"></table>
</div>
</body>
<!-- 全局js -->
<script th:src="@{/js/jquery.min.js}" src="../static/js/jquery.min.js?v=2.1.4"></script>
<script src="https://cdn.bootcss.com/bootstrap-table/1.12.1/bootstrap-table.min.js"></script>
<script src="https://cdn.bootcss.com/bootstrap-table/1.12.0/extensions/treegrid/bootstrap-table-treegrid.js"></script>
<script src="https://cdn.bootcss.com/jquery-treegrid/0.2.0/js/jquery.treegrid.min.js"></script>
<!-- layer javascript -->
<script th:src="@{/js/plugins/layer/layer.min.js}" src="../static/js/plugins/layer/layer.min.js"></script>
<script type="text/javascript">
    var $table = $('#table');

    $(function () {
        getRepository();
    });

    function changeRep(obj) {
        //获取被选中的option标签选项
        var value = obj.options[obj.selectedIndex].value;
        if (value) {
            var json = $.get('/sys/repository/findRepTreegridById.do?id=' + value,function(data,status){
                $table.bootstrapTable('load', data.result);
            });
        }
    }

    //获取资源库列表并选中第一个
    function getRepository() {
        $.ajax({
            type: 'GET',
            async: false,
            url: '/sys/repository/findRepList.do',
            data: {},
            success: function (data) {
                var list = data.result;
                for (var i = 0; i < list.length; i++) {
                    $("#repositoryId").append('<option value="' + list[i].id + '">' + list[i].repName + '</option>');
                }
                if (list.length > 0) {
                    var id = list[0].id;
                    $("#repositoryId").val(id);
                    getScriptList(id);
                }
            },
            error: function () {
                alert("请求失败！请刷新页面重试");
            },
            dataType: 'json'
        });
    }

    //根据资源库ID获取资源库中脚本
    function getScriptList(id) {
        $table.bootstrapTable({
            ///sys/repository/findRepTreegridById.do?id=
            url: '/sys/repository/findRepTreegridById.do?id=' + id,            //请求后台的URL（*）
            method: 'GET',            //请求方式（*）
            idField: 'id',
            striped: true,                      //是否显示行间隔色
            cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
            responseHandler: function (res) {
                return res.result;
                /*return {
                    "total": res.result.totalElements,//总页数
                    "rows": res.result.content//数据列表
                };*/
            },
            //dataType:'jsonp',
            columns: [
                {
                    field: 'check', checkbox: true, formatter: function (value, row, index) {
                        if (row.check == true) {
                            // console.log(row.serverName);
                            //设置选中
                            return {checked: true};
                        }
                    }
                }, {
                    field: 'text',
                    title: '脚本名称',
                    formatter: 'statusFormatter'
                }, {
                    field: 'extra',
                    title: '脚本路径'
                },
                {field: 'operate', title: '操作', align: 'center', events: operateEvents, formatter: 'operateFormatter'},
            ],

            // bootstrap-table-treegrid.js 插件配置 -- start

            //在哪一列展开树形
            treeShowField: 'text',
            //指定父id列
            parentIdField: 'pid',

            onResetView: function (data) {
                //console.log('load');
                $table.treegrid({
                    initialState: 'collapsed',// 所有节点都折叠
                    // initialState: 'expanded',// 所有节点都展开，默认展开
                    treeColumn: 1,
                    // expanderExpandedClass: 'glyphicon glyphicon-minus', //图标样式
                    // expanderCollapsedClass: 'glyphicon glyphicon-plus',
                    onChange: function () {
                        $table.bootstrapTable('resetWidth');
                    }
                });

                //只展开树形的第一级节点
                // $table.treegrid('getRootNodes').treegrid('expand');

            },
            onCheck: function (row) {
                var datas = $table.bootstrapTable('getData');
                // 勾选子类
                selectChilds(datas, row, "id", "pid", true);

                // 勾选父类
                selectParentChecked(datas, row, "id", "pid")

                // 刷新数据
                $table.bootstrapTable('load', datas);
            },

            onUncheck: function (row) {
                var datas = $table.bootstrapTable('getData');
                selectChilds(datas, row, "id", "pid", false);
                $table.bootstrapTable('load', datas);
            },
            // bootstrap-table-treetreegrid.js 插件配置 -- end
        });
    }

    // 格式化按钮
    function operateFormatter(value, row, index) {
        if (row.objectType == 'transformation') {
            return [
                '<button type="button" class="RoleOfdetail btn-small btn-primary" style="margin-right:15px;"><i class="fa fa-plus" ></i>&nbsp;详情</button>',
                '<button type="button" class="RoleOfedit btn-small btn-primary" style="margin-right:15px;"><i class="fa fa-pencil-square-o" ></i>&nbsp;编辑</button>'
                /*,'<button type="button" class="RoleOfdelete btn-small btn-primary" style="margin-right:15px;"><i class="fa fa-trash-o" ></i>&nbsp;删除</button>'*/
            ].join('');
        }
    }

    // 格式化类型
    function typeFormatter(value, row, index) {
        if (value === 'menu') {
            return '菜单';
        }
        if (value === 'button') {
            return '按钮';
        }
        if (value === 'api') {
            return '接口';
        }
        return '-';
    }

    // 格式化状态
    function statusFormatter(value, row, index) {
        if (row.objectType == 'transformation') {
            return '<span><img src=\'/img/trans.png\'/>' + value + '</span>';
            //return '<span '+'style="position: absolute; overflow: hidden; z-index: 3; opacity: 1; background: url(\'/img/folder.png\') center center no-repeat; "'+'>'+value+'</span>';
        } else {
            return '<span><img src=\'/img/folder.png\'/>' + value + '</span>';
        }
        /*if (value === 1) {
            return '<span class="label label-success">正常</span>';
        } else {
            return '<span class="label label-default">锁定</span>';
        }*/
    }

    //初始化操作按钮的方法
    window.operateEvents = {
        'click .RoleOfdetail': function (e, value, row, index) {
            detail(row);
        },
        'click .RoleOfdelete': function (e, value, row, index) {
            del(row.id);
        },
        'click .RoleOfedit': function (e, value, row, index) {
            update(row.id);
        }
    };
</script>
<script>
    /**
     * 选中父项时，同时选中子项
     * @param datas 所有的数据
     * @param row 当前数据
     * @param id id 字段名
     * @param pid 父id字段名
     */
    function selectChilds(datas, row, id, pid, checked) {
        for (var i in datas) {
            if (datas[i][pid] == row[id]) {
                datas[i].check = checked;
                selectChilds(datas, datas[i], id, pid, checked);
            }
            ;
        }
    }

    function selectParentChecked(datas, row, id, pid) {
        for (var i in datas) {
            if (datas[i][id] == row[pid]) {
                datas[i].check = true;
                selectParentChecked(datas, datas[i], id, pid);
            }
            ;
        }
    }

    function test() {
        var selRows = $table.bootstrapTable("getSelections");
        if (selRows.length == 0) {
            alert("请至少选择一行");
            return;
        }

        var postData = "";
        $.each(selRows, function (i) {
            postData += this.id;
            if (i < selRows.length - 1) {
                postData += "， ";
            }
        });
        alert("你选中行的 id 为：" + postData);

    }

    function detail(row) {
        var id = row.id;
        var path = row.extra;
        var text = row.text;
        var transRepositoryId = $("#repositoryId").val();
        var url = "jsonData.shtml?repositoryId=" + transRepositoryId + "&scriptPath=" + path + "&scriptName=" + text;
        var index = layer.open({
            type: 2,
            title: '脚本详情',
            maxmin: true, //开启最大化最小化按钮
            area: ["80%", '80%'],
            skin: 'layui-layer-rim',
            content: url
        });
        //layer.full(index);
    }

    function del(id) {
        alert("del 方法 , id = " + id);
    }

    function update(id) {
        alert("update 方法 , id = " + id);
    }


</script>
</html>